package sar

import groovy.transform.ToString;

class User {

	transient springSecurityService
	static hasOne=[student:Student,courseCoordinator:CourseCoordinator,tutor:Tutor,staff:Staff]
	String fullname;
	String username
	String password
	String email
	String address
	boolean enabled = true
	boolean accountExpired
	boolean accountLocked
	boolean passwordExpired

	static constraints = {
		username blank: false, unique: true
		password blank: false
		fullname blank:false, nullable:true
		email email:true,nullable:true
		address blank:false , nullable:true
		student blank:true, nullable:true, unique:true
		courseCoordinator blank:true, nullable:true, unique:true
		tutor blank:true, nullable:true, unique:true
		staff blank:true, nullable:true, unique:true
	}
	static mappedBy=[student:'user']

	static mapping = { password column: '`password`' }

	Set<Role> getAuthorities() {
		UserRole.findAllByUser(this).collect { it.role } as Set
	}

	def beforeInsert() {
		encodePassword()
	}

	def beforeUpdate() {
		if (isDirty('password')) {
			encodePassword()
		}
	}

	protected void encodePassword() {
		password = springSecurityService.encodePassword(password)
	}
	public String toString(){
		return this.fullname;
	}
}
